import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2024-12-26
 * Time: 23:15
 */
public class test1 {
    /*
    LeetCode 315  计算右侧小于当前元素的个数
     */
    // 两个数组用于接收新数组


    int[] ret;
    int[] index;   // 用于标记下标
    int[] tmpIndex;
    int[] tmpNums;
    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        ret = new int[n];
        index = new int[n];
        tmpIndex = new int[n];
        tmpNums = new int[n];
        for(int i=0;i<n;i++){
            index[i]=i;
        }

        mergeSort(nums,0,n-1);
        List<Integer> l = new ArrayList<>();
        for(int x:ret){
            l.add(x);
        }
        return l;
    }

    public void mergeSort(int[] nums,int left,int right){
        if(left>=right){
            return;
        }
        // 1.根据中间元素划分区间
        int mid = (right-left)/2+left;
        // [left,mid] [mid+1,right]

        // 2.处理左右两个区间
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);

        // 3.处理一左一右的情况
        int cur1 = left,cur2 = mid+1,i=0;
        while(cur1<=mid && cur2<=right){
            if(nums[cur1]<=nums[cur2]){
                tmpNums[i] = nums[cur2];
                tmpIndex[i++] = index[cur2++];   //同时进行修改
            }else{
                ret[index[cur1]] += right-cur2+1;
                tmpNums[i] = nums[cur1];
                tmpIndex[i++] = index[cur1++];
            }
        }

        // 4. 合并数组
        while(cur1<=mid){
            tmpNums[i] = nums[cur1];
            tmpIndex[i++] = index[cur1++];
        }
        while(cur2<=right){
            tmpNums[i] = nums[cur2];
            tmpIndex[i++] = index[cur2++];
        }
        for(int j=left ;j<=right;j++){
            nums[j] = tmpNums[j-left];
            index[j]=tmpIndex[j-left];
        }
    }
}
